#!/bin/sh

check_metrics() {
  local CLUSTER_NAME="${1:-$CLUSTER_NAME}"
  local CLUSTER_POD_IP

  CLUSTER_POD_IP="$(kubectl get pod -n "$CLUSTER_NAMESPACE" \
    -l "app=StackGresCluster,stackgres.io/cluster-name=$CLUSTER_NAME,stackgres.io/cluster=true" \
    -o=jsonpath='{ .items[].status.podIP }')"
  CLUSTER_POD_IP="$(printf %s "$CLUSTER_POD_IP" | head -n 1)"
  for METRIC in pg_settings_shared_buffers_bytes pg_stat_activity_count node_filesystem_size_bytes \
    pgbouncer_show_stats_total_query_count pg_table_bloat_real_size
  do
    if wait_until eval 'kubectl exec -i -n "$CLUSTER_NAMESPACE" curl \
          -- curl -s -f "http://$CLUSTER_POD_IP:9187/metrics" \
          | grep -q "^$METRIC"'
    then
      echo "Exporter metric $METRIC was found"
    else
      echo "Exporter metric $METRIC wasn't found"
    fi
  done

  if ! kubectl get sgcluster -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME" --template '{{ .spec.pods.disableEnvoy }}' | grep -qxF true
  then
    if kubectl exec -i -n "$CLUSTER_NAMESPACE" curl \
      -- curl -s -f "http://$CLUSTER_POD_IP:8001/stats/prometheus" \
      | grep -q "^envoy_postgres_ingress_postgres_sessions"
    then
      echo "Envoy metric envoy_postgres_ingress_postgres_sessions was found"
    else
      echo "Envoy metric envoy_postgres_ingress_postgres_sessions wasn't found"
      return 1
    fi

    for ENVOY_CLUSTER in patroni_cluster postgres_cluster postgres_cluster_pool
    do
      if kubectl exec -i -n "$CLUSTER_NAMESPACE" curl \
        -- curl -s -f "http://$CLUSTER_POD_IP:8001/stats/prometheus" \
        | grep "^envoy_cluster_upstream_cx_active" \
        | grep -q "envoy_cluster_name=\"$ENVOY_CLUSTER\""
      then
        echo "Envoy metric envoy_cluster_upstream_cx_active for cluster $ENVOY_CLUSTER was found"
      else
        echo "Envoy metric envoy_cluster_upstream_cx_active for cluster $ENVOY_CLUSTER wasn't found"
        return 1
      fi
    done
  fi
}
